package com.zl.learning.thread;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

public class TesstThread {

    public static void main(String[] args) {
        new Thread(() -> {
            Stream.iterate(0, n -> n + 1).limit(10).forEach(r -> {
                try {
                    MyQuery.myQuery.put(r);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            try {
                MyQuery.start();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        System.out.println("Thread start");
    }

    static class MyQuery {
        static final BlockingQueue<Integer> myQuery = new LinkedBlockingQueue<Integer>(10);

        public static void start() throws InterruptedException {
            Integer a;
            while (true) {
                a = myQuery.take();
                System.out.println(a);
            }
        }
    }

    static class Test1 {
        public static void main(String[] args) throws InterruptedException {
            Thread t1 = new Thread(() -> {
                boolean start = true;
                while (start) {
                    System.out.println("I'm runing...");
                    String threadName = Thread.currentThread().getName();
                    System.out.println(threadName);
                    try {
                        TimeUnit.SECONDS.sleep(2);
                    } catch (InterruptedException e) {
                        start = false;
                        System.out.println("I'm destory...");
                    }
                }
            });
            t1.start();
            TimeUnit.SECONDS.sleep(1);
            t1.setName("aaaaa");
            TimeUnit.SECONDS.sleep(3);
            t1.setName("bbbb");
            TimeUnit.SECONDS.sleep(4);
            t1.interrupt();
        }
    }

    public static class Test2 {
        public static void main(String[] args) {
            Thread thread = new Thread(() -> {
                System.out.println("HelloWorld");
                throw new RuntimeException("Exception");
            });
            thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
                @Override
                public void uncaughtException(Thread t, Throwable e) {
                    e.printStackTrace();
                    System.out.println(t.getName());
                    System.out.println(e.getMessage());
                }
            });
            thread.start();
        }
    }
}

